import React, { useState, useEffect } from 'react';
import { Table, Button, Tag, Space, Modal, message } from 'antd';
import { DeleteOutlined, EyeOutlined, PlusOutlined } from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import { datasetService } from '../services';

const DatasetList = () => {
  const [datasets, setDatasets] = useState([]);
  const [loading, setLoading] = useState(false);
  const [deleteModalVisible, setDeleteModalVisible] = useState(false);
  const [selectedDataset, setSelectedDataset] = useState(null);
  const navigate = useNavigate();

  // 从datasetService获取数据，这里不再需要单独的模拟数据

  useEffect(() => {
    // 初始加载数据
    fetchDatasets();
    
    // 设置定时器，每30秒刷新一次数据
    const intervalId = setInterval(fetchDatasets, 1000);
    
    // 组件卸载时清理定时器
    return () => clearInterval(intervalId);
  }, []);

  const fetchDatasets = async () => {
    setLoading(true);
    try {
      // 使用datasetService获取数据集列表
      const response = await datasetService.getDatasets();
      // 适配数据格式，确保与表格列匹配
      setDatasets(Array.isArray(response) ? response : response.data || []);
    } catch (error) {
      console.error('获取数据集失败:', error);
      message.error('获取数据集失败，请稍后重试');
    } finally {
      setLoading(false);
    }
  };

  const handleDelete = async () => {
    if (!selectedDataset) return;
    
    try {
      // 使用datasetService删除数据集
      await datasetService.deleteDataset(selectedDataset.id);
      // 更新本地状态
      setDatasets(datasets.filter(item => item.id !== selectedDataset.id));
      message.success('数据集删除成功');
      setDeleteModalVisible(false);
      setSelectedDataset(null);
    } catch (error) {
      console.error('删除数据集失败:', error);
      message.error('删除数据集失败，请稍后重试');
    }
  };

  const showDeleteConfirm = (dataset) => {
    setSelectedDataset(dataset);
    setDeleteModalVisible(true);
  };

  const handleView = (id) => {
    navigate(`/dataset/${id}`);
  };

  const handleCreate = () => {
    navigate('/create');
  };

  const getStatusTag = (status) => {
    switch (status) {
      case 'PENDING':
        return <Tag color="default">待处理</Tag>;
      case 'PROCESSING':
        return <Tag color="processing">处理中</Tag>;
      case 'COMPLETED':
        return <Tag color="success">已完成</Tag>;
      case 'FAILED':
        return <Tag color="error">失败</Tag>;
      default:
        // 对于没有status字段的数据，添加默认状态
        return <Tag color="default">已创建</Tag>;
    }
  };

  const columns = [
    {
      title: '数据集名称',
      dataIndex: 'name',
      key: 'name',
      ellipsis: true,
    },
    {
      title: '描述',
      dataIndex: 'description',
      key: 'description',
      ellipsis: true,
    },
    {
      title: '状态',
      key: 'status',
      render: (_, record) => getStatusTag(record.status),
    },
    {
      title: '创建时间',
      dataIndex: 'createdAt',
      key: 'createdAt',
      render: (text) => new Date(text).toLocaleString(),
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Space size="middle">
          <Button 
            type="text" 
            icon={<EyeOutlined />} 
            onClick={() => handleView(record.id)}
          >
            查看
          </Button>
          <Button 
            type="text" 
            danger 
            icon={<DeleteOutlined />} 
            onClick={() => showDeleteConfirm(record)}
          >
            删除
          </Button>
        </Space>
      ),
    },
  ];

  return (
    <div>
      <div style={{ marginBottom: 16, display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '16px', backgroundColor: '#fafafa', borderRadius: '8px' }}>
        <h2>数据集列表</h2>
        <Button 
          type="primary" 
          icon={<PlusOutlined />} 
          onClick={handleCreate}
        >
          创建数据集
        </Button>
      </div>
      
      <Table 
        columns={columns} 
        dataSource={datasets} 
        rowKey="id" 
        loading={loading}
        pagination={{ pageSize: 10 }}
      />

      <Modal
        title="确认删除"
        open={deleteModalVisible}
        onOk={handleDelete}
        onCancel={() => setDeleteModalVisible(false)}
        okText="删除"
        okType="danger"
        cancelText="取消"
      >
        <p>确定要删除数据集「{selectedDataset?.name}」吗？此操作不可撤销。</p>
      </Modal>
    </div>
  );
};

export default DatasetList;